import React, { useState, useEffect } from 'react';
import styles from '../styles/Home.module.css';

export interface HistoryItem {
  id: string;
  timestamp: number;
  type: 'voice' | 'text';
  userInput: string;
  modelResponse?: string;
  audioUrl?: string;
}

interface HistoryRecordProps {
  onSelectHistory?: (item: HistoryItem) => void;
}

const HistoryRecord: React.FC<HistoryRecordProps> = ({ onSelectHistory }) => {
  const [historyItems, setHistoryItems] = useState<HistoryItem[]>([]);
  const [expandedItems, setExpandedItems] = useState<Record<string, boolean>>({});

  // 从localStorage加载历史记录
  useEffect(() => {
    try {
      const savedHistory = localStorage.getItem('llm-voice-history');
      if (savedHistory) {
        const parsedHistory = JSON.parse(savedHistory) as HistoryItem[];
        setHistoryItems(parsedHistory);
      }
    } catch (error) {
      console.error('加载历史记录失败:', error);
    }
  }, []);

  // 切换展开/折叠状态
  const toggleExpand = (id: string) => {
    setExpandedItems(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };

  // 清除所有历史记录
  const clearAllHistory = () => {
    if (window.confirm('确定要清除所有历史记录吗？此操作不可恢复。')) {
      localStorage.removeItem('llm-voice-history');
      setHistoryItems([]);
    }
  };

  // 删除单条历史记录
  const deleteHistoryItem = (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    const newHistory = historyItems.filter(item => item.id !== id);
    setHistoryItems(newHistory);
    localStorage.setItem('llm-voice-history', JSON.stringify(newHistory));
  };

  // 选择历史记录
  const handleSelectHistory = (item: HistoryItem) => {
    if (onSelectHistory) {
      onSelectHistory(item);
    }
  };

  // 格式化时间
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
  };

  if (historyItems.length === 0) {
    return (
      <div className={styles.historySection}>
        <h2 className={styles.sectionTitle}>历史记录</h2>
        <p>暂无历史记录</p>
      </div>
    );
  }

  return (
    <div className={styles.historySection}>
      <div className="flex justify-between items-center mb-4">
        <h2 className={styles.sectionTitle}>历史记录</h2>
        <button 
          className="btn btn-secondary"
          onClick={clearAllHistory}
        >
          清除所有记录
        </button>
      </div>
      
      <div className={styles.historyList}>
        {historyItems.slice().reverse().map(item => (
          <div 
            key={item.id} 
            className={styles.historyItem}
            onClick={() => toggleExpand(item.id)}
          >
            <div className={styles.historyHeader}>
              <div className={styles.historyMeta}>
                <span className={styles.historyType}>
                  {item.type === 'voice' ? '🎤 语音输入' : '⌨️ 文本输入'}
                </span>
                <span className={styles.historyTime}>{formatTime(item.timestamp)}</span>
              </div>
              <div className={styles.historyActions}>
                <button 
                  className="btn"
                  onClick={(e) => handleSelectHistory(item)}
                >
                  重用
                </button>
                <button 
                  className="btn"
                  onClick={(e) => deleteHistoryItem(item.id, e)}
                >
                  删除
                </button>
              </div>
            </div>
            
            <div className={`${styles.historyContent} ${expandedItems[item.id] ? styles.expanded : ''}`}>
              <div className={styles.historyInputOutput}>
                <div>
                  <strong>用户输入:</strong>
                  <p>{item.userInput}</p>
                </div>
                
                {item.modelResponse && (
                  <div className="mt-2">
                    <strong>模型回复:</strong>
                    <p>{item.modelResponse}</p>
                  </div>
                )}
                
                {item.audioUrl && item.audioUrl.startsWith('blob:') && (
                  <div className="mt-2">
                    <strong>录音文件:</strong>
                    <p><small>(录音文件在页面刷新后不可用)</small></p>
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default HistoryRecord; 